<!-- Horizontal Form -->
<div class="box box-info">
    <div class="box-header with-border">
        <h3 class="box-title">用户添加</h3>
        <h3 class="msg"></h3>
    </div>
    <!-- /.box-header -->
    <!-- form start -->
    <form class="form-horizontal">
        <div class="box-body">

            <div class="form-group">
                <label for="usernameId" class="col-sm-2 control-label" >用户名</label>
                <div class="col-sm-8">
                    <input type="text" name="username" class="form-control" id="usernameId"
                    placeholder="不能为空" pattern="^.{3,8}$" required=true>
                </div>
            </div>
            <div class="form-group" id="pwdDiv">
                <label for="passwordId" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-8">
                    <input type="password" name="password" class="form-control" id="passwordId"
                    placeholder="不能为空" required=true>
                </div>
            </div>
            <div class="form-group" id="pwdsDiv">
                <label for="againPasswordId" class="col-sm-2 control-label">密码确认</label>
                <div class="col-sm-8">
                    <input type="password" name="againPassword" class="form-control" id="againPasswordId"
                           placeholder="不能为空" required="required">
                </div>
            </div>
            <div class="form-group">
                <label for="telephoneId" class="col-sm-2 control-label">手机号</label>
                <div class="col-sm-8">
                    <input type="number" name="telephone" class="form-control" id="telephoneId"
                           placeholder="不能为空" >
                </div>
            </div>
            <div class="form-group">
                <label for="boyId" class="col-sm-2 control-label">性别</label>
                <div class="col-sm-8">
                    男 <input type="radio" name="gender" value="1" checked="checked">
                    女 <input type="radio" name="gender" value="0"  >
                </div>
            </div>
            <!--          <div class="form-group">-->
            <!--            <label for="deptId" class="col-sm-2 control-label">部门</label>-->
            <!--            <div class="col-sm-10">-->
            <!--              <input type="text" class="form-control load-sys-dept" readonly="readonly" id="deptId" placeholder="上级部门">-->
            <!--            </div>-->
            <div class="form-group">
                <label for="ageId" class="col-sm-2 control-label">年龄</label>
                <div class="col-sm-8">
                    <input type="number" name="age" class="form-control" id="ageId" placeholder="这里输入您的年华">
                </div>
            </div>
            <div class="form-group">
                <label for="signId" class="col-sm-2 control-label">个性签名</label>
                <div class="col-sm-8">
                    <input type="text" name="sign" class="form-control" id="signId">
                </div>
            </div>
            <div class="form-group">
                <label for="hobbyId" class="col-sm-2 control-label">爱号</label>
                <div class="col-sm-8">
                    <input type="text" name="hobby" class="form-control" id="hobbyId">
                </div>
            </div>
            <div class="form-group">
                <label for="rolesId" class="col-sm-2 control-label">角色</label>
                <div class="col-sm-8" id="rolesId"></div>
            </div>

        </div>
        <!-- /.box-body -->
        <div class="box-footer">
            <button type="button" class="btn btn-default btn-cancel">退出</button>
            <button type="button" class="btn btn-info pull-right btn-save">保存</button>
        </div>
        <!-- /.box-footer -->
    </form>

</div>
<script type="text/javascript" src="bower_components/ztree/jquery.ztree.all.min.js"></script>
<script type="text/javascript" src="bower_components/layer/layer.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        //页面加载完成以后加载角色信息并初始化页面
        doLoadRoles();
        //事件注册
        $(".box-footer")
            .on("click", ".btn-cancel", doCancel)   //触发取消
            .on("click", ".btn-save", doSaveOrUpdate);  //触发新增/修改
    });

    //取消
    function doCancel() {
        $("#mainContentId").removeData("rowData");
        $("#mainContentId").load("/modules/sys/user_list.html");
    }

    //新增/修改
    function doSaveOrUpdate() {
        let rowData = $("#mainContentId").data("rowData"); //读取修改的数据
        //1.获取表单数据
        let data = doGetEditFormData();
        if (rowData) {
            data.id = rowData.id; //如果有数据就是进行修改,id等于选中的id
            data.password=null;
        }
        //用户输入校验
        if(data.username==""){
            alert("请输入用户名!");return;
        }
        if(!rowData){
            if(data.password==""){
                alert("请输入密码!");return;
            }
            if($("#againPasswordId").val()==""){
                alert("请输入确认密码!");return;
            }
            if(data.password.length<6){
                alert("密码不能小于6位");return;
            }
            if(data.password!=$("#againPasswordId").val()){
                alert("两次密码输入不一致!");return;
            }
        }
        if(data.telephone==""){
            alert("请输入手机号!");return;
        }
        let checkPhone = /^1[34578][0-9]{9}$/
        if(!checkPhone.test(data.telephone)){
            alert("请填写正确的手机号!");return;
        }
        if(data.age<0||data.age==""){
            alert("请正确填写年龄");return;
        }else if (data.age>120){
            alert("不相信有这么长寿的人...");return;
        }
        if(data.roleId==null){
            alert("必须选择一个角色!");return;
        }
        let check = checkNameAndPhone(data);    //进行用户名和电话重复校验
        if(!rowData){
            if (check!=null){
                alert(check);return;
            }
        }else{
            if(data.username!=rowData.username){    //用户名不同则校验用户
                if(check=="该用户已被注册!"){
                    alert(check);return;
                }
            }
            if(data.telephone!=rowData.telephone){  //电话不同则校验电话
                if(check=="该手机号已被使用!"){
                    alert(check);return;
                }
            }
        }
        //2.发起异步请求
        let url = `${baseUrl}/shoppingback/ddUsersInfo`;
        let method = rowData ? "put" : "post";  //如果有数据就是put,没数据就是post
        $.ajax({
            method: method,
            url: url,
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            crossDomain: true,
            xhrFields: {withCredentials: true},
            data: JSON.stringify(data),
            contentType: "application/json",
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    alert(result.msg);
                    doCancel();
                } else {
                    alert(result.msg);
                }
            }
        })
    }

    //添加用户:读取输入的数据
    function doGetEditFormData() {
        //获取用户输入的数据
        let params = {
            username: $("#usernameId").val(),
            password: $("#passwordId").val(),
            age: $("#ageId").val(),
            gender: $("input[name='gender']:checked").val(),
            telephone: $("#telephoneId").val(),
            sign: $("#signId").val(),
            hobby: $("#hobbyId").val()
        }
        //获取选择的角色
        let roleId = $("#rolesId input[name='roleId']:checked").val();
        params.roleId = roleId;
        return params;
    }

    //读取角色信息,并载入修改信息
    function doLoadRoles() {
        let url = `${baseUrl}/shoppingback/role/selectRoles`;
        $.ajax({
            url, crossDomain: true, xhrFields: {withCredentials: true},
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    doInitPageRoles(result.data);//显示角色按钮
                    doInitFormData();//修改操作:载入表单数据
                } else {
                    alert(result.msg);
                }
            }
        })
    }

    //修改用户:读取表单数据
    function doInitFormData() {
        let data = $("#mainContentId").data("rowData");
        if (!data) return; //如果不是修改则返回
        $("#pwdDiv").remove();
        $("#pwdsDiv").remove();
        //初始化用户信息
        $("#usernameId").val(data.username);
        $("#ageId").val(data.age);
        $("#genderId").val(data.gender);
        $("#telephoneId").val(data.telephone);
        $("#signId").val(data.sign);
        $("#hobbyId").val(data.hobby);
        //初始化用户角色信息
        let id = data.roleId;
        $(`#rolesId input[value=${id}]`).prop("checked", true); //根据id进行默认勾选


    }

    //显示角色按钮
    function doInitPageRoles(data) {//List<CheckBox>
        //1.获取角色要显示的位置对象
        let div = $("#rolesId");
        div.empty();
        //2.迭代数据，将数据追加到div
        let input = `<input type='radio' name='roleId' value='[id]'> [name]   ` //载入角色按钮
        console.log(data);
        data.forEach(item => {
            //记住每次replace时都会产生一个新的字符串对象
            var newInput =
                input.replace("[id]", item.id)
                    .replace("[name]", item.name);
            div.append(newInput)    //插入角色按钮
        });
    }

    //校验用户名和手机号
    function checkNameAndPhone(data) {
        let url= `${baseUrl}/shoppingback/ddUsersInfo/checkNameAndPhone`;
        let message;
        $.ajax({
            url:url,
            data:{"username":data.username,"telephone":data.telephone},
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            async: false,
            success(result){
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                message=result.msg;
            }
        });
        return message;
    }
</script>
    
    
    
    
    
    
    